<!--
  使用步骤
    0. 在项目中加入components/carouse/carouse.vue文件
    1. 在main.js中 引入 import "swiper/swiper-bundle.min.css"
    2. 注册公共组件 util/components.js
      import carouse from "components/carouse/carouse"
      Vue.component("sph-carouse",carouse)
    3. 在组件上使用
        <sph-carouse></sph-carouse>
            props:
              banners: required 必须是一个数组 [banner]
              options: 参照swiper的使用配置(https://www.swiper.com.cn/api/index.html)
            banner数据结构
              {id,imgUrl}
-->



<template>
  <div class="swiper-container"  ref="carouse">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="{id,imgUrl} in banners" :key="id">
        <img :src="imgUrl" />
      </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>

    <!-- 如果需要导航按钮 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</template>

<script>
  import swiper from 'swiper/swiper-bundle.min.js';
  import {checkArr} from "util/util"
  export default {
    name: "sph-carouse",
    props:{
      banners:{
        type:Array,
        required:true,
        validator(arr){
          for(let item of arr){
            //当前对象所有属性名组成的数组
            let flag = checkArr(Object.keys(item),["id","imgUrl"]);
            //如果flag一直为ture就代表传入的数据是合法的
            if(!flag){
              return false;
            }
          }
          return true;
        }
      },
      options:{
        type:Object,
        default(){
          return {}
        }
      }
    },
    watch:{
      banners:{
        handler(){
          //只有banners产生变化了 handler才会执行
          //当前这个$nextTick对应的cb一定会在banners数据对应的界面完成渲染后执行!!!!!
          this.$nextTick(()=>{
            new swiper (this.$refs.carouse, {
              direction: 'horizontal', // 垂直切换选项
              loop: true, // 循环模式选项
              pagination: {
                el: '.swiper-pagination',
              },
              navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
              },
              ...this.options
            })
          })
        },
        deep:true,
        immediate:true
      }
    }
  }
</script>

<style scoped>

</style>